// import { eSocket } from '@/interface/eSocket';

import { useSocketMsg } from '@/store/socket_msg';
import { eventBus } from './event_bus';

// import { Router } from 'vue-router';
class CustomWebSocket {
  private _url: string = import.meta.env.VITE_WS_URL;
  //   private _url: string = `ws://172.16.65.212:8282/`;
  // private _url: string = `ws://172.16.60.33:8080/api/v1/ws/client`;
  private static instance: CustomWebSocket | null;
  private ws!: WebSocket;
  // private router: Router | null = null;
  /**
   * 心跳重连时间
   */
  private heartTime: number = parseInt(Math.random() * 60 + 30 + '') * 1000;
  /**
   * setTimeout 延迟心跳的计时器
   */
  private heartInterval: NodeJS.Timeout | number = 0;
  /**
   * 检测 如果心跳重连失败,没有收到响应则关闭连接并且重新开启ws的计时器
   */
  // private heartReconnectTimeout: number = 0;
  private reconnectTimeout: any = null;
  private realClose: boolean = false;
  // private token: string = '';
  private first: boolean = true; //初始化为true，重连以后为false，用来在内网环境下，如果websocket重连，不进行排队申请云电脑的操作
  private constructor() {
    this.first = true;
    this.initWs();
  }
  public static getInstance(): CustomWebSocket {
    if (!this.instance) {
      this.instance = new CustomWebSocket();
    }
    return this.instance;
  }
  // public setToken(token: string) {
  //   // this.token = token;
  // }
  // public setRouter(router: Router) {
  //   this.router = router;
  // }
  /**
   * 初始化websocket
   */
  public initWs() {
    if (!this._url) {
      this._url = `ws://${location.hostname}`;
    }
    // try {
    if (this.ws && (this.ws.readyState === this.ws.OPEN || this.ws.readyState === this.ws.CONNECTING)) return;
    // this.ws = new WebSocket(this._url + ':7077/ws');
    this.ws = new WebSocket(this._url + ':8080/ws');
    //   this.ws = new WebSocket(`${this._url}/${Store.state.userinfo!.token}`);
    //   console.debug(`WebSocket地址：${this._url}/${Store.state.userinfo!.token}`);

    this.ws.onmessage = (data: any) => this.wsOnMessage(data);
    this.ws.onerror = (e: any) => this.wsOnError(e);
    this.ws.onopen = () => this.wsOnOpen();
    this.ws.onclose = (e: any) => this.wsOnClose(e);
    // this.ws.send = (data: any) => {
    //   this.wsSend(data);
    // };
    this.reconnectTimeout = null;
    //   Store.commit(WS, this);
    // } catch (err) {
    //   console.error('initWs出错', err);
    // }
  }
  public wsOnMessage(e: any) {
    console.debug('收到消息', e.data);
    const storeSocketMsg = useSocketMsg();

    // open_surplus_notice(0, '232323232332dsfsdfs');
    try {
      let data = JSON.parse(e.data);
      // const data = parseWsMsg(e.data);
      switch (data.type) {
        /**
         * 心跳
         */
        case 'status':
          storeSocketMsg.status = data.data.status;
          break;
        case 'sample_status':
          storeSocketMsg.sample_status = data.data;
          break;
        case 'error':
          storeSocketMsg.error = data.data;
          break;
        // case 0:
        // case 1:
        // case 2:
        // case 3:
        // case 4:
        // case 5:
        case 'alarm':
          storeSocketMsg.notices.push({ ...data.data, isRead: false });
          break;
        default:
          break;
      }
    } catch (error) {
      console.log('解析json出错', e);
      console.error('解析json出错', e);
    }
  }

  public wsOnError(e: any) {
    console.error('ws error', e);
    this.realClose = false;
    this.reconnect();
  }
  public wsOnOpen() {
    console.info('ws 连接成功,开始接收消息;first:' + this.first);
    eventBus.emit('refresh_status', 2);
    if (this.first) {
      // 模拟效果
      // openNormalNotification({type: eSocket.NORMAL_MSG, title: '房间1011正在进行查房', content : '查房人：李慧', sub_content: '查房时间： 2022-01-01 12：11：11', msg_id: 12});
    } else {
      console.info('开始判断是否被回收' + this.first);
    }
    this.checkHeartJump();
  }

  public wsOnClose(e: any) {
    console.debug('通知关闭wsOnclose', e);

    this.reset();
    if (!this.realClose) {
      console.info('在接收到关闭事件以后，重连ws');
      eventBus.emit('refresh_status', 1);
      this.reconnect();
    }
  }
  /**
   * 关闭websocket
   */
  public wsClose() {
    this.realClose = true;
    console.info('关闭连接');
    this.ws.close();
  }
  public wsSend(data: any) {
    // console.log('send data', data);
    console.debug('send data', data);
    if (typeof data === 'string') {
      this.ws.send(data);
    } else {
      this.ws.send(JSON.stringify(data));
    }
  }

  /**
   * 重连
   */
  public reconnect() {
    if (this.realClose) {
      return;
    }
    this.reconnectFn();
  }
  public reconnectFn() {
    if (this.reconnectTimeout) {
      clearTimeout(this.reconnectTimeout);
      this.reconnectTimeout = null;
    }
    this.reconnectTimeout = setTimeout(() => {
      this.first = false;
      this.reset();
      this.initWs();
      console.info('重连ws');
      //检查是否已经回收
    }, this.heartTime);
  }
  /**
   * 重置心跳
   */
  private reset(): CustomWebSocket {
    clearInterval(this.heartInterval as any);
    // clearTimeout(this.heartReconnectTimeout);
    return this;
  }
  /**
   * 心跳检测
   */
  checkHeartJump() {
    this.heartInterval = setInterval(() => {
      this.wsSend({ type: 'heartbeat' });
    }, this.heartTime);
  }
}
export default CustomWebSocket;
